var map;
var nuevo = null;
var panoramio = false;
var buscar_google = false;
var marcadores = new Array();
var panoramioLayer;

function placeMarker(location) {
	if (nuevo != null)
		nuevo.setMap(null);
	nuevo = new google.maps.Marker( {
		position : location,
		map : map
	});
}

$(document)
		.ready(
				function() {

					var latlng = new google.maps.LatLng(-38.416097,
							-63.616671999999994);
					var myOptions = {
						zoom : 5,
						center : latlng,
						mapTypeId : google.maps.MapTypeId.HYBRID
					};
					map = new google.maps.Map(document
							.getElementById("map_canvas"), myOptions);

					if ($('input[name=latitud]').length > 0
							& $('input[name=longitud]').length > 0) {

						if ($('input[name=latitud]')[0].value != ''
								& $('input[name=longitud]')[0].value != '') {

							var coord = new google.maps.LatLng(
									parseFloat($('input[name=latitud]')[0].value),
									parseFloat($('input[name=longitud]')[0].value));
							placeMarker(coord);
						}
						google.maps.event.addListener(map,'click',function(event) {
								placeMarker(event.latLng);
								if($('input[name=latitud]').length > 0 && $('input[name=longitud]').length > 0){
									$('input[name=latitud]')[0].value = event.latLng.lat();
									$('input[name=longitud]')[0].value = event.latLng.lng();
								}
							});
					}
					
					panoramioLayer = new
					google.maps.panoramio.PanoramioLayer();
					
					autocompletar();
					if(typeof window.miFuncion == 'function')
						miFuncion();
					
					if($.cookie('places')!=null){
						mostrarLugares(JSON.parse($.cookie('places')));
					}
					if($.cookie('city')!=null){
						var city =JSON.parse($.cookie('city'));						
						if (city.geometry.viewport) {
							var bounds = new google.maps.LatLngBounds(
									new google.maps.LatLng(city.geometry.viewport.ca.b,city.geometry.viewport.ea.b),
									new google.maps.LatLng(city.geometry.viewport.ca.f,city.geometry.viewport.ea.f)
							);
							map.fitBounds(bounds);
						} else {
							map.setCenter(city.geometry.location);
							map.setZoom(17); 
						}
						$('.titulo_buscar').text(city.formatted_address);
					}

					$('#ver_imagenes').click(function(){
					    panoramio=this.checked;
						if(panoramio){
							panoramioLayer.setMap(map);
						}else{
							panoramioLayer.setMap(null);
						}
							
					});
					$('#buscar_google').click(function(){
						buscar_google=this.checked;
					});
					
					
				});
function autocompletar(){
	var infowindow = new google.maps.InfoWindow();
	var marker = new google.maps.Marker( {
		map : map
	});	
	//places add
	if($('#city2').length > 0){
		var autocomplete2 = new google.maps.places.Autocomplete(
				$("#city2")[0], {
					componentRestrictions: {country: 'ar'},
					types:new Array('(cities)'),
				});

		google.maps.event.addListener(autocomplete2,'place_changed',function(){
			go_to_site(autocomplete2,infowindow,marker);
		});
	}
	if($('#city3').length > 0){
		var autocomplete3 = new google.maps.places.Autocomplete(
				$("#city3")[0], {
					componentRestrictions: {country: 'ar'},
					types:new Array('(cities)'),
				});
	}
	
	//mapa buscar
	if($('#city').length > 0){
		var autocomplete = new google.maps.places.Autocomplete(
				$("#city")[0], {
					componentRestrictions: {country: 'ar'},
					types:new Array('(cities)'),
				});

		google.maps.event.addListener(autocomplete,'place_changed',function(){
			go_to_site(autocomplete,infowindow,marker);
			if($('.titulo_buscar')!=null)
				$('.titulo_buscar').text($("#city").val());
			$.cookie('city',JSON.stringify(autocomplete.getPlace()));
		});
	}
}

function go_to_site(autocomplete,infowindow,marker) {
	infowindow.close();
	var place = autocomplete.getPlace();
	for(var j=0; j<marcadores.length; j++){
		marcadores[j].setMap(null);
	}
	marcadores=new Array();
	buscar(place.formatted_address);
	if(buscar_google)
		buscar_google_places(place.geometry.location.lat(),place.geometry.location.lng());
	
	if (place.geometry.viewport) {
		map.fitBounds(place.geometry.viewport);
	} else {
		map.setCenter(place.geometry.location);
		map.setZoom(5); // Why 17?
		// Because it
		// looks good.
	}

	/*var image = new google.maps.MarkerImage(
			place.icon,
			new google.maps.Size(71, 71),
			new google.maps.Point(0, 0),
			new google.maps.Point(17, 34),
			new google.maps.Size(35, 35));
	marker.setIcon(image);*/
	marker.setPosition(place.geometry.location);

	var address = '';
	if (place.address_components) {
		address = [
				(place.address_components[0]
						&& place.address_components[0].short_name || ''),
				(place.address_components[1]
						&& place.address_components[1].short_name || ''),
				(place.address_components[2]
						&& place.address_components[2].short_name || '') ]
				.join(' ');
	}

	infowindow.setContent('<div><strong>'
			+ place.name + '</strong><br>'
			+ address);
	infowindow.open(map, marker);

	if(panoramio){
		panoramioLayer.setMap(map);
	}
	
	
}

function buscar(ciudad){
	var url ="search_for_city/"+encodeURI(ciudad);
	$.getJSON(url, function(data) {
		mostrarLugares(data);
		$.cookie('places',JSON.stringify(data));
	});
}

function mostrarLugares(data){
	var cant = marcadores.length;
	$('.lugares ul').empty();
	for(var i=0;i<data.places.length;i++){
		$('.lugares ul').append('<li><a href="../places/details/'+data.places[i].id+'">'+data.places[i].title+'</li>');
		var latlng2 = new google.maps.LatLng(data.places[i].latitud,data.places[i].longitud);

		marcadores[cant+i]= new google.maps.Marker({
			position: latlng2,
			title:data.places[i].title,
		}); 
		marcadores[cant+i].setMap(map);
		var image = new google.maps.MarkerImage(
				'../images/marker_sprite_green.png',
				new google.maps.Size(19, 32),
				new google.maps.Point(0, 1));
		marcadores[cant+i].setIcon(image);
		var shadow = new google.maps.MarkerImage(
				'../images/marker_sprite_green.png',
				new google.maps.Size(30, 20),
				new google.maps.Point(27, 14),
				new google.maps.Point(3, 20));
		marcadores[cant+i].setShadow(shadow);
		
		with({id:data.places[i].id}){
			google.maps.event.addListener(marcadores[cant+i], 'click', function(){
				window.location = '../places/details/'+id;		
			});
		}
	}
}

function buscar_google_places(lat,long){
	var url ="search_google/"+lat+"/"+long;
	$.getJSON(url, function(data) {
		var cant = marcadores.length;
		for(var i=0;i<data.results.length;i++){
			var latlng2 = new google.maps.LatLng(data.results[i].geometry.location.lat,data.results[i].geometry.location.lng);

			marcadores[cant+i] = new google.maps.Marker({
				position: latlng2,
				title:data.results[i].name,
			}); 
			marcadores[cant+i].setMap(map);
			
			with ({ reference: data.results[i].reference,marker:marcadores[cant+i] }) {
				google.maps.event.addListener(marcadores[cant+i], 'click', function(){
					url ="google_details/"+reference;
					$.getJSON(url, function(data){
						var infowindow2 = new google.maps.InfoWindow();
						infowindow2.setContent('<h1>'+data.result.name+'</h1>'+
												'<h3>'+data.result.formatted_address+'</h3>'+
												'<a href="'+data.result.url+'" target="blank">mas info</a>');
						infowindow2.open(map,marker);
					});
				});
			}
		}
	});
}